//
// Created by baigui on 21-6-29.
//
#define TAG "MediaPlayer"
#include <MediaPlayer.h>
#include <NDKRender.h>
#include <log.h>
#include "moduleManager.h"

void MediaPlayer::setDataSource(const char *path){
    LOGV("setDataSource");
    char *buf = new char[strlen(path)+1];
    strcpy(buf, path);
    loadDemux(buf);
    if (!mDumex)
        return;
    shared_ptr<MediaStream> stream = mDumex->getStreamInfo();
    while  (stream != nullptr) {
        LOGV("stream info %s   :%d",stream.get()->mime,stream->state);
        if (stream->state == SELCECT){
            LOGV("select stream: %d",stream->id);
            LoadDecoder(stream);
        }
        stream = stream->next;
    }
    if (mVideoRender == nullptr){
        LoadRender();
    }
}


void MediaPlayer::start(){
    LOGV("start");

    if (mVideoDecoder)
        mVideoDecoder->start();

    if (mDumex) {
        mDumex->start();
    }
    if (mVideoRender)
        mVideoRender->start();
}

void MediaPlayer::stop(){

}

void MediaPlayer::pause(){

}

int MediaPlayer::LoadRender(RenderType type) {
    LOGV("LoadRender");
    switch (type) {
        case NDKCodecType:{
            mVideoRender = Module::get_instance().renderModuleManager.getModule(shared_from_this(), &type);
            return 1;
        }
        case Auto:{

        }
        default:
            return 0;
    }

}

int MediaPlayer::setSurface(ANativeWindow* window) {
    LOGV("set window");
    mWindow = window;
    return 0;
}

void MediaPlayer::LoadDecoder(shared_ptr<MediaStream> stream) {
    LOGV("LoadDecoder: %s", stream->mime);
    mVideoDecoder = Module::get_instance().decoderModuleManager.getModule(shared_from_this(), stream.get());
}


VideoRender *MediaPlayer::getVideoRender() {
    return mVideoRender.get();
}

void MediaPlayer::loadDemux(char* path) {
    mDumex = Module::get_instance().demuxModuleManager.getModule(shared_from_this(),path);

}
